package com.wisenet.service.wxpubno;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wisenet.common.ApiConst;
import com.wisenet.common.Const;
import com.wisenet.pojo.respmsgpojo.Music;

/**
 * API工具服务类
 * @author fzh
 *
 */
public class ApiService {
	public static Logger logger = Logger.getLogger(ApiService.class);
	private static final HttpClient client = new HttpClient();
	private static final StringBuffer bufone = new StringBuffer();
	
	/**
	 * 天气查询
	 * @param city
	 * @return
	 */
	public static String getWeather(String city) {
		if (city.length() < 4) {
			return "暂无数据";
		}
		StringBuffer sbf = new StringBuffer();
		try {
			city = city.replaceAll("天气", "").replaceAll("市", "");
			JSONObject json = getJsonByJsoup(ApiConst.MINI_WEATHER_URL + URLEncoder.encode(city, "UTF-8"));
			if (json == null || !json.containsKey("data")) return "暂无数据";
			
			JSONArray array = json.getJSONObject("data").getJSONArray("forecast");
			for (int i = 0; i < array.size(); i++) {
				JSONObject obj = array.getJSONObject(i);
				if (obj == null) return "暂无数据";
				
				if (i == 0) {
					sbf.append("【").append(city).append("】").append("天气预报\n")
					   .append(obj.get("date"))
					   .append(" 温度：").append(obj.get("high")).append(" ~ ").append(obj.get("low"))
					   .append(" 天气：").append(obj.get("type"))
					   .append(" 风向：").append(obj.get("fengxiang")).append("\n");
				} else {
					sbf.append(obj.get("date"))
					   .append(" ").append(obj.get("high")).append(" ~ ").append(obj.get("low"))
					   .append(obj.get("type")).append(" ").append(obj.get("fengxiang")).append("\n");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sbf.toString();
	}
	
	/**
	 * 搜索歌曲音乐
	 * @param name
	 * @return
	 * @throws IOException
	 */
	public static List<Music> searchMusicList(String name) throws Exception {
        JSONObject json = getMusicList(name);
        if (!json.containsKey("song")) {
        	logger.info("MUSIC NOT FOUND");
        	return null;
        }

    	// 随机获取歌曲列表
        List<Music> musicList = new ArrayList<>();
    	JSONArray arr = json.getJSONArray("song");
    	for (int i = 0; arr != null && i < arr.size(); i++) {
    		if (i == Const.MUSIC_LIMIT) {
    			return musicList;
    		}
    		JSONObject songObj = arr.getJSONObject(i);
    		if (StringUtils.isEmpty(songObj.getString("songid"))) {
    			logger.info("SONGID IS NULL");
    			return null;
    		}
    		String musicUrl = getMp3Url(json.getString("songid"));
    		if (musicUrl == null) {
    			logger.info("MUSICURL IS NULL");
    			break;
    		}
    		Music music = new Music();
    		music.setMusicUrl(musicUrl);
    		music.setTitle(json.getString("songname"));
    		music.setDescription(json.getString("artistname"));
    		musicList.add(music);
    	}
		return musicList;
	}
	
	/**
	 * 搜索歌曲音乐
	 * @param name
	 * @return
	 * @throws IOException
	 */
	
	public static JSONObject getMusicList(String name) throws Exception {
		String url = ApiConst.BAIDU_TING_URL + URLEncoder.encode(name, "UTF-8");
        return getJsonByJsoup(url);
	}
	
	/**
	 * 获取歌曲播放链接
	 * @param songid
	 * @return
	 * @throws Exception 
	 */
	public static String getMp3Url(String songid) throws Exception {
		// 解析数据
		JSONObject json = getJsonByJsoup(ApiConst.BAIDU_TING_PLAY_URL + songid);
		if (json.containsKey("bitrate")) {
			// 真正的播放链接
			if (json.getString("bitrate").contains("file_link")) {
				return json.getJSONObject("bitrate").getString("file_link");
			}
		}
		return null;
	}
	
	/**
	 * 请求数据
	 * @param url
	 */
	public static void getReuestData(String url) {
		GetMethod getMethod = null;
		try {
			getMethod = new GetMethod(url);
	   		getMethod.getParams().setParameter("http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY);
	   		int statusCode = client.executeMethod(getMethod);
	   		if (statusCode == HttpStatus.SC_OK) {
	   			InputStream inputStream = getMethod.getResponseBodyAsStream();   
	   			BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
	   			String str = "";
	   			while ((str = br.readLine()) != null) {
	   				bufone.append(str+System.getProperty("line.separator"));
	   			}
	   			str = null;
	   			br.close();
	   			inputStream.close();
	   		}
		} catch(Exception e) {
	    	logger.info("抓取出错: " + e.getMessage());
	    } finally {
	    	if (getMethod != null) {
	    		getMethod.releaseConnection();
	    	}
	    }
	}
	
	public static String talk(String msg) throws Exception {
		String url = ApiConst.TALK_URL + URLEncoder.encode(msg, "UTF-8");
		JSONObject json = getJsonByJsoup(url);
		return !"0".equals(json.getString("result")) ? null : json.getString("content").replaceAll("\\{br\\}", "\n");
	}
	
	public static JSONObject getJsonByJsoup(String url) throws Exception {
		Document doc = Jsoup.connect(url).timeout(6000).ignoreContentType(true).get();
		Elements elements = doc.getElementsByTag("body");
		if (elements != null) {
			String song = elements.get(0).text().replaceAll("&quot;", "\"");
			return JSONObject.parseObject(song);
		}
		return null;
	}
	
}
